// filename: frontend/src/components/SearchBar/SearchBar.vue

<template>
  <div class="search-wrapper" @click.stop>
    <div class="search-bar-container">
      <input
        class="search-input"
        type="text"
        placeholder="标签搜索(标签之间要空格): 歌曲, 歌手, 语种(包括河曲), 日期(20250823), 状态(直播, minilive等)..."
        v-model="searchText"
        @keydown.enter="executeSearch"
        @focus="onFocus"
      />
      <div class="search-icon" @click="executeSearch">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
            <path d="M16.172 11l-5.364-5.364 1.414-1.414L20 12l-7.778 7.778-1.414-1.414L16.172 13H4v-2z"></path>
        </svg>
      </div>
    </div>

    <SearchResults
      v-show="showResults"
      :results="searchResults"
      @itemClick="handleItemClick"
    />
  </div>
</template>

<script setup>
import { defineEmits, defineExpose, ref, watch, defineProps } from "vue";
import { request } from "@/utils/request"; // 【核心修改1】导入 request
import SearchResults from "@/components/SearchResults/SearchResults.vue";

const emit = defineEmits(["search", "focus"]);

const props = defineProps({
  searchContext: {
    type: String,
    default: 'global'
  },
  localData: {
    type: Array,
    default: () => []
  }
});

const searchText = ref("");
const searchResults = ref(null);
const showResults = ref(false);
let debounceTimer = null;

watch(searchText, (newQuery) => {
  emit("search", { type: "keyword", value: newQuery });
  clearTimeout(debounceTimer);

  if (!newQuery.trim()) {
    searchResults.value = null;
    showResults.value = false;
    return;
  }

  debounceTimer = setTimeout(() => {
    if (props.searchContext === 'local') {
      performLocalSearch(newQuery);
    } else if (props.searchContext === 'playlist_global') {
      fetchPlaylistNameSuggestions(newQuery);
    } else {
      fetchGlobalSearchResults(newQuery);
    }
  }, 300);
});

// --- 【核心修改2】重写 fetchPlaylistNameSuggestions ---
const fetchPlaylistNameSuggestions = async (query) => {
  try {
    const data = await request({
      url: `/api/public/playlists/search-suggestions?q=${encodeURIComponent(query)}`,
      method: 'GET'
    });
    if (Array.isArray(data)) {
      searchResults.value = { playlists: data };
      showResults.value = data.length > 0;
    } else {
      showResults.value = false;
    }
  } catch (error) {
    showResults.value = false;
  }
};

// --- 【核心修改3】重写 fetchGlobalSearchResults ---
const fetchGlobalSearchResults = async (query) => {
  try {
    const data = await request({
      url: `/api/search?q=${encodeURIComponent(query)}`,
      method: 'GET'
    });
    if (data) {
      if (data.dates) {
        data.dates = data.dates.map((d) => d.replace(/-/g, ""));
      }
      searchResults.value = data;
      showResults.value = Object.values(data).some(
        (arr) => Array.isArray(arr) && arr.length > 0
      );
    }
  } catch (error) {
    showResults.value = false;
  }
};

// --- 其他函数保持不变 ---
const performLocalSearch = (query) => {
  const lowerQuery = query.toLowerCase();
  const results = {
    songs: [],
    artists: new Set(),
    statuses: new Set(),
    languages: new Set()
  };
  
  props.localData.forEach(song => {
    if (song.title && song.title.toLowerCase().includes(lowerQuery)) {
      results.songs.push(song);
    }
    if (song.cover_artists && song.cover_artists.toLowerCase().includes(lowerQuery)) {
      song.cover_artists.split(',').forEach(name => {
        if (name.trim().toLowerCase().includes(lowerQuery)) results.artists.add(name.trim());
      });
    }
    if (song.original_artists && song.original_artists.toLowerCase().includes(lowerQuery)) {
      song.original_artists.split(',').forEach(name => {
        if (name.trim().toLowerCase().includes(lowerQuery)) results.artists.add(name.trim());
      });
    }
    if (song.status_name && song.status_name.toLowerCase().includes(lowerQuery)) {
      results.statuses.add(song.status_name);
    }
    if (song.language_name && song.language_name.toLowerCase().includes(lowerQuery)) {
      results.languages.add(song.language_name);
    }
  });

  searchResults.value = {
    songs: results.songs,
    artists: Array.from(results.artists).map(name => ({ name })),
    statuses: Array.from(results.statuses).map(name => ({ name })),
    languages: Array.from(results.languages).map(name => ({ name })),
    dates: [],
    song_types: [],
  };
  
  showResults.value = results.songs.length > 0 || results.artists.size > 0 || results.statuses.size > 0 || results.languages.size > 0;
};

const handleItemClick = (item) => {
  const value = item.data.name || item.data.title || (item.type === 'playlist' ? item.data.name : item.data);
  searchText.value = value;
  showResults.value = false;
};

const executeSearch = () => {
  showResults.value = false;
};

const onFocus = () => {
  emit("focus");
};

const setSearchTextAndExecute = (text) => {
  searchText.value = text;
  showResults.value = false;
};

const closeSearchResults = () => {
  showResults.value = false;
};

defineExpose({
  setSearchTextAndExecute,
  closeSearchResults,
});
</script>

<style scoped>
.search-wrapper {
  position: relative;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 101;
}
.search-bar-container {
    width: 90%;
    max-width: 800px;
    position: relative;
    display: flex;
    justify-content: center;
}
.search-input {
  width: 100%;
  height: 40px;
  padding: 0 40px 0 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background-color: #f8f8f8;
  font-size: 14px;
}
.search-icon {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #888;
}
.search-icon:hover {
    color: #333;
}
.search-wrapper > :deep(.search-results-container) {
  position: absolute;
  top: 55px;
  width: 90%;
  max-width: 800px;
  z-index: 100;
}
</style>